package spring.webflux;

import lombok.SneakyThrows;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.netty.http.server.HttpServer;
import spring.webflux.handler.PersonnelHandler;
import spring.webflux.service.PersonnelService;
import spring.webflux.service.PersonnelServiceImpl;

import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;

public class Server {

    @SneakyThrows
    public static void main(String[] args) {
        Server server = new Server();
        server.createReactorServer();
        System.out.println("enter to exit");
        System.in.read();
    }

    public RouterFunction<ServerResponse> routerFunction() {
        PersonnelService personnelService = new PersonnelServiceImpl();
        PersonnelHandler personnelHandler = new PersonnelHandler(personnelService);
        return RouterFunctions.route(
                GET("/personnel/{id}").and(accept(APPLICATION_JSON)), personnelHandler::getPersonnelById)
                .andRoute(GET("/personnel").and(accept(APPLICATION_JSON)), personnelHandler::getAllPersonnel);
    }

    public void createReactorServer() {
        RouterFunction<ServerResponse> route = routerFunction();
        HttpHandler httpHandler = toHttpHandler(route);
        ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);

        HttpServer httpServer = HttpServer.create();
        httpServer.port(55936).handle(adapter).bindNow();
    }
}
